﻿@using Microsoft.AspNetCore.Components.WebAssembly.Services;
@using Microsoft.Extensions.Logging;
@using System.Reflection;
@inject LazyAssemblyLoader AssemblyLoader
@inject ILogger<App> Logger

<Router AppAssembly="@typeof(App).Assembly"
        AdditionalAssemblies="@lazyLoadedAssemblies"
        OnNavigateAsync="@OnNavigateAsync">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(DocLayout)" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(DocLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {

    private List<Assembly> lazyLoadedAssemblies = new()
    {
        typeof(Masa.Blazor.Docs.ServiceCollectionExtensions).Assembly
    };

    private async Task OnNavigateAsync(NavigationContext args)
    {
        try
        {
            var path = args.Path;
            path = path.Split("?").First().Split("#").First().ToLowerInvariant();

            if (path is "blazor/components/image-captcha" or "blazor/labs/watermark")
            {
                var assemblies = await AssemblyLoader.LoadAssembliesAsync(
                    new[] { "SkiaSharp.wasm", "SkiaSharp.Views.Blazor.wasm" });
                lazyLoadedAssemblies.AddRange(assemblies);
            }
            else if (path == "blazor/components/forms")
            {
                var assemblies = await AssemblyLoader.LoadAssembliesAsync(
                    new[] { "Util.Reflection.wasm" });
                lazyLoadedAssemblies.AddRange(assemblies);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("Error: {Message}", ex.Message);
        }
    }

}
